/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elementsDefense.towers;

import elementsDefense.enemies.*;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.control.Control;
import elementsDefense.Main;
import elementsDefense.map.Map.Dir;
import elementsDefense.map.Tile;

/**
 *
 * @author Ricardo
 */
public class SearchAndDestroyControl extends AbstractControl{

    float range;
    float reloadTime;
    float firingTime;
    Tower tower;
    BasicEnemy currentTarget;

    public SearchAndDestroyControl(float range, float reloadTime, float firingTime, Tower tower) {
        this.range = range;
        this.reloadTime = reloadTime;
        this.firingTime = firingTime;
        this.tower = tower;
    }
    
    
    float passed=0;
    @Override
    protected void controlUpdate(float tpf) {
        passed+=tpf;
        if(passed>reloadTime){
            //search
            if(currentTarget==null || tower.location.distance(currentTarget.getLocation())>range || !currentTarget.isAlive()){
                currentTarget = null;
                for (BasicEnemy basicEnemy : EnemyWave.enemies) {
                    if(tower.location.distance(basicEnemy.getLocation())<range){
                        currentTarget=basicEnemy;
                    }
                }
            }
            
            if(currentTarget!=null){
                //prepare to fire
                if(passed<reloadTime+firingTime){
                    tower.prepareToFire(currentTarget, (passed-reloadTime)/firingTime);
                }else{//fire
                    passed=0;
                    tower.fire(currentTarget);
                }
            }else{
                passed=reloadTime;
            }
        }
    }

    @Override
    protected void controlRender(RenderManager rm, ViewPort vp) {
    }

    public Control cloneForSpatial(Spatial spatial) {
        final SearchAndDestroyControl control = new SearchAndDestroyControl(range, reloadTime, firingTime, tower);
        /* Optional: use setters to copy userdata into the cloned control */
        // control.setIndex(i); // example
        control.setSpatial(spatial);
        return control;
    }
}
